package com.hzncc.flowable_diboot.controller.customer;

import com.diboot.core.binding.QueryBuilder;
import com.diboot.core.controller.BaseCrudRestController;
import com.diboot.core.util.BeanUtils;
import com.diboot.core.vo.JsonResult;
import com.diboot.core.vo.Pagination;
import com.diboot.iam.annotation.BindPermission;
import com.diboot.iam.annotation.Log;
import com.diboot.iam.annotation.OperationCons;
import com.hzncc.flowable_diboot.dto.CustomerDTO;
import com.hzncc.flowable_diboot.dto.SalesTeamDTO;
import com.hzncc.flowable_diboot.entity.Customer;
import com.hzncc.flowable_diboot.entity.SalesTeam;
import com.hzncc.flowable_diboot.excel.listener.CustomerImportListener;
import com.hzncc.flowable_diboot.excel.listener.CustomerOldCrmListener;
import com.hzncc.flowable_diboot.excel.model.CustomerImportModel;
import com.hzncc.flowable_diboot.excel.model.CustomerOldCrmImportModel;
import com.hzncc.flowable_diboot.excel.service.MultiSheetExcelImportService;
import com.hzncc.flowable_diboot.service.CustomerService;
import com.hzncc.flowable_diboot.service.SalesTeamService;
import com.hzncc.flowable_diboot.service.impl.TianYanChaService;
import com.hzncc.flowable_diboot.util.ConstantUtil;
import com.hzncc.flowable_diboot.vo.CustomerDetailVO;
import com.hzncc.flowable_diboot.vo.CustomerListVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * 客户 相关rest接口
 *
 * @author MyName
 * @version 1.0
 * @date 2024-05-15
 * Copyright © MyCorp
 */
@Slf4j
@RequestMapping("/customer")
@BindPermission(name = "客户")
@RestController
public class CustomerController extends BaseCrudRestController<Customer> {

    @Autowired
    private CustomerService customerService;


    @Autowired
    private SalesTeamService salesTeamService;

    @Autowired
    private TianYanChaService tianYanChaService;

    @Autowired
    private MultiSheetExcelImportService multiSheetExcelImportService;


    /**
     * 查询资源对象的列表VO记录
     * <p>
     * url请求参数示例: ?fieldA=abc&pageSize=20&pageIndex=1&orderBy=id
     * </p>
     *
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_LIST)
    @BindPermission(name = OperationCons.LABEL_LIST, code = OperationCons.CODE_READ)
    @GetMapping()
    public JsonResult<List<CustomerListVO>> getListVOMapping(CustomerDTO queryDto, Pagination pagination, String type) throws Exception {
        //return super.getViewObjectList(queryDto, pagination, CustomerListVO.class);
        // 区分公海和我的客户
        return customerService.selectCustom(queryDto, pagination, type);
    }

    /**
     * 根据id查询资源对象的详情VO
     *
     * @param id ID
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_DETAIL)
    @BindPermission(name = OperationCons.LABEL_DETAIL, code = OperationCons.CODE_READ)
    @GetMapping("/{id}")
    public JsonResult<CustomerDetailVO> getDetailVOMapping(@PathVariable("id") String id) throws Exception {
        //CustomerDetailVO detailVO = customerService.getViewObject(id, CustomerDetailVO.class);
        CustomerDetailVO detailVO = customerService.getDetail(id);
        return JsonResult.OK(detailVO);
    }


    /**
     * 创建资源对象数据
     *
     * @param customer
     * @return JsonResult
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_CREATE)
    @BindPermission(name = OperationCons.LABEL_CREATE, code = OperationCons.CODE_WRITE)
    @PostMapping()
    public JsonResult<?> createModelMapping(@RequestBody Customer customer) throws Exception {

        return customerService.createCustomer(customer);
    }

    /**
     * 批量创建资源对象数据
     *
     * @param customerList
     * @return JsonResult
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_BATCH_UPDATE)
    @BindPermission(name = OperationCons.LABEL_UPDATE, code = OperationCons.CODE_WRITE)
    @PostMapping("/batch")
    public JsonResult<?> batchCreateModelMapping(@RequestBody List<Customer> customerList) throws Exception {
        boolean success = customerService.createEntities(customerList);
        log.debug("批量新建数据 客户 {}", success ? "成功" : "失败");
        return JsonResult.OK(success);
    }

    /**
     * 根据id更新资源对象
     *
     * @param customer
     * @return JsonResult
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_UPDATE)
    @BindPermission(name = OperationCons.LABEL_UPDATE, code = OperationCons.CODE_WRITE)
    @PutMapping("/{id}")
    public JsonResult<?> updateModelMapping(@PathVariable("id") String id, @RequestBody Customer customer) throws Exception {
        boolean success = customerService.updateEntity(customer);
        log.debug("更新数据 客户:{} {}", id, success ? "成功" : "失败");
        return JsonResult.OK(success);
    }

    /**
     * 根据id删除资源对象
     *
     * @param id
     * @return
     * @throws Exception
     */
    @Log(operation = ConstantUtil.PERMISSION_DELETE_LABEL)
    @BindPermission(name = ConstantUtil.PERMISSION_DELETE_LABEL, code = ConstantUtil.PERMISSION_DELETE)
    @DeleteMapping("/{id}")
    public JsonResult<?> deleteModelMapping(@PathVariable("id") String id) throws Exception {
        boolean success = customerService.deleteEntity(id);
        log.debug("删除数据 客户:{} {}", id, success ? "成功" : "失败");
        return JsonResult.OK(success);
    }

    /**
     * 根据ids集合删除资源对象
     *
     * @param ids
     * @return
     * @throws Exception
     */
    @Log(operation = ConstantUtil.PERMISSION_DELETE_LABEL)
    @BindPermission(name = ConstantUtil.PERMISSION_DELETE_LABEL, code = ConstantUtil.PERMISSION_DELETE)
    @PostMapping("/batch-delete")
    public JsonResult<?> deleteEntityMapping(@RequestBody List<String> ids) throws Exception {
        boolean success = customerService.deleteEntities(ids);
        log.debug("批量删除数据 客户:{} {}", ids, success ? "成功" : "失败");
        return JsonResult.OK(success);
    }


    /**
     * 客户转移
     *
     * @param uid 接收人id
     * @return
     * @author 陈广煜
     * @date 2024/5/20
     */
    @Log(operation = OperationCons.LABEL_WRITE)
    @BindPermission(name = OperationCons.LABEL_WRITE,code = OperationCons.CODE_WRITE)
    @GetMapping("/trans")
    public JsonResult<?> transform(@RequestParam String uid, @RequestParam List<String> ids) {
        return customerService.trans(uid, ids);
    }

    /**
     * 放入公海
     *
     * @return
     * @author 陈广煜
     * @date 2024/5/21
     */
    @Log(operation = OperationCons.LABEL_WRITE)
    @BindPermission(name = OperationCons.LABEL_WRITE,code = OperationCons.CODE_WRITE)
    @PostMapping("/putSea")
    public JsonResult<?> pushSeas(@RequestBody Map<String, String> param) {
        String id = param.get("id");
        String reason = param.get("reason");
        Customer cus = customerService.getEntity(id);
        String oldUid = cus.getPrincipal();
        cus.setPrincipal("");
        cus.setIsEnter(0);
        cus.setEnterTime(LocalDateTime.now());
        cus.setEnterReason(reason);
        cus.setEnterDays(0L);
        customerService.updateEntity(cus);
        // 销售团队处置 移除负责人
        List<SalesTeam> oldTeam = salesTeamService.getEntityList(QueryBuilder
                .toQueryWrapper(new SalesTeamDTO()
                        .setCustomerId(cus.getId()).setMember(oldUid)));
        salesTeamService.deleteEntities(oldTeam);
        return JsonResult.OK();
    }

    /**
     * 基础信息查询
     *
     * @return
     * @author 陈广煜
     * @date 2024/5/21
     */
    @Log(operation = OperationCons.LABEL_WRITE)
    @BindPermission(name = OperationCons.LABEL_WRITE,code = OperationCons.CODE_WRITE)
    @GetMapping("/baseInfo")
    public JsonResult<?> baseInfo(@RequestParam String id) {
        Customer entity = customerService.getEntity(id);
        Map<String, String> baseInfo = new HashMap<>();
        baseInfo.put("province", entity.getProvince());
        baseInfo.put("name", entity.getName());
        baseInfo.put("city", entity.getCity());
        baseInfo.put("creditCode", entity.getCreditCode());
        return JsonResult.OK(baseInfo);
    }

    /**
     * 公海转移
     *
     * @return
     * @author 陈广煜
     * @date 2024/5/22
     */
    @Log(operation = ConstantUtil.TENANT_TRANS_PERMISSION_LABEL)
    @BindPermission(name = ConstantUtil.TENANT_TRANS_PERMISSION_LABEL,code = ConstantUtil.TENANT_TRANS_PERMISSION_CODE)
    @GetMapping("/transSea")
    public JsonResult<?> transSea(@RequestParam String customerId, @RequestParam String sea) {
        customerService.transSea(customerId, sea);
        return JsonResult.OK();
    }

    /**
     * 分配
     *
     * @param cusId 客户id
     * @param uid   用户id
     * @return
     * @author 陈广煜
     * @date 2024/5/22
     */
    @Log(operation = ConstantUtil.PERMISSION_DISTRIBUTE_LABEL)
    @BindPermission(name = ConstantUtil.PERMISSION_DISTRIBUTE_LABEL,code = ConstantUtil.PERMISSION_DISTRIBUTE)
    @GetMapping("/distribute")
    public JsonResult<?> distribute(@RequestParam String cusId, @RequestParam String uid) {
        customerService.distribute(cusId, uid);
        return JsonResult.OK();
    }

    /**
     * 天眼查搜索企业
     *
     * @return
     * @author 陈广煜
     * @date 2024/5/24
     */
    @Log(operation = OperationCons.LABEL_READ)
    @BindPermission(name = OperationCons.LABEL_READ,code = OperationCons.CODE_READ)
    @GetMapping("/enterpriseInfo")
    public JsonResult<?> getEnterpriseInfo(@RequestParam String name, Pagination pagination) {
        return tianYanChaService.search(name, pagination.getPageSize(), pagination.getPageIndex());
    }

    /**
     * 天眼查获取企业详情
     *
     * @return
     * @author 陈广煜
     * @date 2024/5/24
     */
    @Log(operation = OperationCons.LABEL_READ)
    @BindPermission(name = OperationCons.LABEL_READ,code = OperationCons.CODE_READ)
    @GetMapping("/enterpriseDetail")
    public JsonResult<?> getEnterpriseDetail(@RequestParam String name) {
        return tianYanChaService.detail(name);
    }

    /**
     * 获取sap编号
     *
     * @return
     * @author 陈广煜
     * @date 2024/6/13
     */
    @Log(operation = OperationCons.LABEL_READ)
    @BindPermission(name = OperationCons.LABEL_READ,code = OperationCons.CODE_READ)
    @GetMapping("/getSapNo")
    public JsonResult<?> getSapNo(String customerId){
        Customer cus = customerService.getEntity(customerId);
        return JsonResult.OK(cus.getSn());
    }

    /**
     * 导入旧系统数据
     * @return
     */
    @Log(operation = OperationCons.LABEL_WRITE)
    @PostMapping("/importOldSystemData")
    public JsonResult<?> importOldSystemData(@RequestParam("file") MultipartFile file, @RequestParam Map<String, Object> params) throws Exception {
        List<CustomerOldCrmImportModel> list = multiSheetExcelImportService.readSingleSheet(file, CustomerOldCrmImportModel.class, CustomerOldCrmListener.class);
        Set<String> errList = customerService.convertAndSave(list);
        return JsonResult.OK(errList);
    }

    @GetMapping("/validate")
    public JsonResult<?> validate(String field,String value) {
        return JsonResult.OK(customerService.validateUnique(field,value));
    }


}